#include "AvDecoder.h"
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <sys/stat.h>
#include "Package.h"

#include <cstddef>

/// @brief 获取文件字节长度
/// @param f 文件路径
/// @return 字节数

long file_length(const char *f)
{
    struct stat st;
    stat(f, &st);
    return st.st_size;
}

int AvDecoder::run(bool loop, decode_callback callback) {
    FILE *file = fopen(m_file_path, "r");
    // 读取帧数据的buffer大小 2048  (位深：16bit)
    

    uint8_t pcm_buf[2048];

    long file_len = file_length(m_file_path);

    size_t read_count;
    while (read_count = fread(pcm_buf, 1, sizeof(pcm_buf), file), read_count > 0){ 
        std::cout << "read file byte: " << read_count << std::endl;

        // uint8_t* dst = (uint8_t*)malloc(read_count);
        
        // memcpy(dst, pcm_buf, read_count);

        std::unique_ptr<uint8_t[]> pData{ new uint8_t[read_count] };
        auto ptr = pData.get();

        memcpy(ptr, pcm_buf, read_count);

        auto packae = Package(ptr, read_count);
        callback(std::move(packae));
    }

    fclose(file);

    //文件读取完毕
    std::cout << "read file finished!!" << std::endl;

    return 0;
}
